import type { Request, ResponseToolkit } from "@hapi/hapi";
import Bcrypt from "bcryptjs";
import Hapi from "@hapi/hapi";
import { userSchema, userResult } from "../schema/index";
import { User, Notes } from "../../model/index";

let route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  path: "/register",
  method: "post",
  handler: async (r: any, h: ResponseToolkit) => {
    try {
      const { account, password } = r.payload as any;
      const hashedPassword = await Bcrypt.hash(password, 10);
      let user: any = await new User({ account, password: hashedPassword });
      if (user) {
        const notes: any = await new Notes({
          pid: user._id,
          personal: {
            data: {
              img: "",
            },
            type: -1,
          }, //个人资料
          selfEvaluation: {
            data: null,
            type: 0,
          }, //自我评价
          educationalBg: {
            data: null,
            type: 1,
          }, //教育背景
          workExperience: {
            data: null,
            type: 2,
          }, //工作经历
          certificate: {
            data: null,
            type: 3,
          }, //证书
          skills: {
            data: null,
            type: 4,
          }, //技能
          hobby: {
            data: null,
            type: 5,
          }, //兴趣爱好
          isVertical: false,
          status: true,
          noteName: user.account + "的简历",
        });
        await notes.save();
        await user.note.push(notes._id);
        await user.save();
        return { message: "用户创建成功", code: 200, data: true };
      }
    } catch (err: any) {
      console.log(err, "err");
      if (err.code === 11000) {
        // 如果出现重复键值错误，则返回适当的错误消息
        return h
          .response({
            error: { message: "账户名已存在，请使用其他账户名", code: 11000 },
          })
          .code(400);
      } else {
        // 否则返回通用错误消息
        console.log("error here");
        return h
          .response({
            error: { message: "创建用户时出现错误", code: err.code || 500 },
          })
          .code(500);
      }
    }
  },
  options: {
    payload: {
      parse: true, // 解析请求体
      allow: "application/json", // 允许JSON格式的请求体
    },
    auth: false,
    tags: ["api", "foo"],
    validate: {
      payload: userSchema,
    },
    plugins: {
      "hapi-swagger": {
        responses: {
          "200": {
            description: "Success!",
          },
          "400": {
            description: "Bad Request",
          },
          "404": {
            description: "Not Found",
          },
          "500": {
            description: "Internal Server Error",
          },
        },
        produces: ["application/json"],
        consumes: ["application/json"],
      },
    },
  },
};
export default route;
